import Toast from '../../component/vant/toast/toast';
import Dialog from '../../component/vant/dialog/dialog';
var app = getApp()
var fetchApi = require("../../utils/httpPost.js")
const areaJson = require("../../utils/area_json.js")
const CryptoJS = require("../../utils/aesUtil.js")
var common_Js = require("../../component/common.js")
const message = '是否要解绑该企业？';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    hasUserInfo: false,
    is_mer: 0,
    is_test: 0,
    is_admin: 0,
    shop_name:'',
    pageIndex: 1,
    pageSize: 10,
    loading: false,
    netWork: true,
    isLoading: true,
    isLogin:0,
    isHasUnionId:0,
    user_type:7,
    showDialog:false,
    showPhoneDialog:false,
    dialogTitle:'绑定企业',
    dialogPhoneTitle:'绑定手机号',
    shop_no:'',
    shop_id:0,
    phone_num:'去绑定',
    passwords:'',
    from_page:'',
    town_name:'',
    village_name:'',
    platformName:'',
    platformTitle:'卓宇智慧巡检',
    weatherInfo:{},
    columsCount:4,
    user_no:'',
    isOpenRange:0,
    isOpenFirework:0,
    isOpenZhili:0,
    isOpenWelding:0,
    isHasDeviceType9:0,

    banners:[
      {
        'id': 1,
        'imgUrl': "https://en.zcchengyi.com/checkimg/sectionlink/link1.jpg",
        'linkId': "10",
        'linkType': "product",
        'sort': "1",
        'state': "1",
        'viewHeight': "450",
        'viewWidth': "1080",
      },
      {
        'id': 2,
        'imgUrl': "https://en.zcchengyi.com/checkimg/sectionlink/link2.jpg",
        'linkId': "10",
        'linkType': "product",
        'sort': "1",
        'state': "1",
        'viewHeight': "450",
        'viewWidth': "1080",
      },
      {
        'id': 3,
        'imgUrl': "https://en.zcchengyi.com/checkimg/sectionlink/link3.jpg",
        'linkId': "10",
        'linkType': "product",
        'sort': "1",
        'state': "1",
        'viewHeight': "450",
        'viewWidth': "1080",
      },
    ],
    btns_view_show:[
      {name:'访问申请',icon:'https://en.zcchengyi.com/checkimg/image/dianhan-shenqing-icon.png',bindTap:'toapply',isclean:0,btnType:'jiance'},
        ],
    btns_view: [
      //温度电流
      {name:'制粒机监测',icon:'https://en.zcchengyi.com/checkimg/image/jiance-icon.png',bindTap:'',isclean:0,btnType:'jiance',
      linkUrl:"/pages/shop/index?type=4&position=1"},
      {name:'锅炉测温',icon:'https://en.zcchengyi.com/checkimg/image/jiance-icon.png',bindTap:'',isclean:0,btnType:'jiance',
      linkUrl:"/pages/shop/index?type=9&position=2"},
      {name:'油罐检测',icon:'https://en.zcchengyi.com/checkimg/image/jiance-icon.png',bindTap:'',isclean:0,btnType:'jiance',
      linkUrl:"/pages/shop/index?type=10&position=3"},


      {name:'筒仓测量',icon:'https://en.zcchengyi.com/checkimg/image/store-icon.png',bindTap:'',isclean:0,btnType:'tongcang',
      linkUrl:"/pages/shop/index?type=5&oil=0"},
      {name:'油罐测量',icon:'https://en.zcchengyi.com/checkimg/image/youguanche-icon.png',bindTap:'',isclean:0,btnType:'youguan',
      linkUrl:"/pages/shop/index?type=5&oil=1"},

      {name:'物料管理',icon:'https://en.zcchengyi.com/checkimg/image/wuliao-qr-code-icon.png',bindTap:'scanCode',isclean:0,btnType:'tongcang'},

      {name:'固定区域动火',icon:'https://en.zcchengyi.com/checkimg/image/dianhan-shenqing-icon.png',bindTap:'scanCode',isclean:0,btnType:'guding'},

      {name:'固定动火审批',icon:'https://en.zcchengyi.com/checkimg/image/dianhanji-record-icon.png',bindTap:'goDeviceRecord',isclean:0,btnType:'tongcang'},
      
      {name:'作业申请',icon:'https://en.zcchengyi.com/checkimg/image/dianhan-shenqing-icon.png',bindTap:'',isclean:0,btnType:'tongcang',
      linkUrl:"/pages/firework/list/index"},
      
      {name:'筒仓测量工具',icon:'https://en.zcchengyi.com/checkimg/image/store-tool-icon.png',bindTap:'',isclean:0,btnType:'tongcang',
      linkUrl:"/pages/tool/index"},
      {name:'访问审批',icon:'https://en.zcchengyi.com/checkimg/image/dianhanji-record-icon.png',bindTap:'',isclean:0,btnType:'jiance',
          linkUrl:"/pages/apply/checkRecord/index"},
    ],
    btns_view_apply: [
      {name:'访问申请',icon:'https://en.zcchengyi.com/checkimg/image/dianhan-shenqing-icon.png',bindTap:'toapply',isclean:0,btnType:'jiance'},
      {name:'制粒机访问',icon:'https://en.zcchengyi.com/checkimg/image/jiance-icon.png',bindTap:'',isclean:0,btnType:'jiance',
      linkUrl:"/pages/apply/shop/index?type=4&position=1"},
      {name:'锅炉访问',icon:'https://en.zcchengyi.com/checkimg/image/jiance-icon.png',bindTap:'',isclean:0,btnType:'jiance',
      linkUrl:"/pages/apply/shop/index?type=9&position=2"},
    ]
  },
  onLoad(){
    wx.getPrivacySetting({
      success: res => {
        console.log(res) // 返回结果为: res = { needAuthorization: true/false, privacyContractName: '《xxx隐私保护指引》' }
        if (res.needAuthorization) {
          // 需要弹出隐私协议
        } else {
        }
      },
      fail: () => {},
      complete: () => {}
    })
  },
  onShow: function(res) {
    var that = this
    var isLogin = app.getStorageSync("isLogin");
    console.log('isLogin',isLogin)
    this.setData({
      isLogin: isLogin
    });
    if(isLogin == 1){
      if(that.data.from_page == 'login'){
        that.onHttpGetUserInfo()
      }else if(that.data.from_page == ''){
        that.reLogin()
      }
    }
    else{
      // that.reLogin()
      that.setData({ isLoading: false, loading: true })
    }
    that.data.from_page = ''
  },
  reLogin: function(){
    var that = this
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        console.log("code", res.code)
        fetchApi.httpPost('/user/wxlogin', { code: res.code }, function (res) {
          console.log("登录返回数据", res)
          if(res.data.code ==0){
            that.onHttpGetUserInfo()
          }
          that.setData({ isLoading: false, loading: true })
        }, function (res) { 
          that.setData({ isLoading: false, loading: true })
        })
      },fail(res){
        that.setData({ isLoading: false, loading: true })
      }
    })
  },
  openDialog:function(){
    if(this.data.shop_id > 0){//解绑
      Dialog.confirm({
        title: '解绑企业',
        message,
      });
    }else{//绑定
      // this.setData({showDialog:true})
      this.scanCode();
    }
  },
  /**
   * 获取页面数据的 http请求
   */
  onHttpGetUserInfo: function () {
    var that = this
    fetchApi.httpPost('/user/getUserInfoById', {
    }, function (res_info) {
      console.log('res_info',res_info);
      app.setStorageSync("user_type", res_info.data.data.user_type);
      app.setStorageSync("shop_id", res_info.data.data.shop_id);
      app.setStorageSync("shop_name", res_info.data.data.shop_name);
      app.setStorageSync("phone_num", res_info.data.data.phone_num);
      app.setStorageSync("is_has_unionid", res_info.data.data.is_has_unionid);
      app.setStorageSync("is_test", res_info.data.data.is_test);
      app.setStorageSync("user_no", res_info.data.data.user_no);
      

      that.data.isHasUnionId = res_info.data.data.is_has_unionid;
      app.globalData.userInfo = app.getStorageSync("userInfo");
      that.data.shop_id = res_info.data.data.shop_id;
      that.data.is_test = res_info.data.data.is_test;
      if (res_info.data.data.shop_id && res_info.data.data.shop_id > 0) {
        that.data.btns_view_show = res_info.data.data.modules
      }
      that.data.isOpenWelding = res_info.data.data.isOpenWelding;

      that.data.isHasDeviceType9 = res_info.data.data.isHasDeviceType9;
      that.setData({
        isHasDeviceType9: res_info.data.data.isHasDeviceType9,
        user_no: res_info.data.data.user_no,
        shop_id: res_info.data.data.shop_id,
        shop_name:res_info.data.data.shop_name,
        user_type:res_info.data.data.user_type,
        phone_num:res_info.data.data.phone_num,
        userInfo: app.globalData.userInfo,
        town_name: res_info.data.data.town_name,
        village_name: res_info.data.data.village_name,
        btns_view_show: that.data.btns_view_show,
        platformTitle:res_info.data.data.platformTitle,
        weatherInfo:res_info.data.data.weather.weatherinfo,
        banners: res_info.data.data.banners,
        is_test: res_info.data.data.is_test,
        isLoading: false, loading: true, netWork: true
      })
      wx.hideNavigationBarLoading() //完成停止加载
      wx.stopPullDownRefresh() //停止下拉刷新
    }, function () {
      // Toast.fail('请求user/getUserInfo失败')
     })
  },
  openDialog:function(){
    if(this.data.shop_id > 0){//解绑
      Dialog.confirm({
        title: '解绑企业',
        message,
      });
    }else{//绑定
      // this.setData({showDialog:true})
      this.scanCodeBandShop();
    }
  },
  scanCodeBandShop: function () {
    var that = this
    var isLogin = app.getStorageSync("isLogin");
    if (!isLogin) {
      wx.navigateTo({
        url: '../login/index',
      })
    } else {
      wx.scanCode({
        success: (res) => {
          console.log("扫码结果", res);
          var qrcontent = res.result;
          console.log('扫码结果',qrcontent)
          var json_param = {}
          if (qrcontent.indexOf('qrtype') < 0) {//加密过的数据
            qrcontent = CryptoJS.Decrypt(res.result)//解密
            console.log('解密：qrcontent',qrcontent)
            json_param = JSON.parse(qrcontent);
          }
          var isshop_indexof = qrcontent.indexOf('shop');
          var that = this
          if (isshop_indexof >= 0) {
            fetchApi.httpPost('/user/bandShop', {
              shop_no: json_param["num"],
            }, function (res) {
              console.log('res', res)
              if(res.data.code == 0){
                Toast.success(res.data.msg)
                that.data.shop_id = res.data.data.id
                that.data.shop_no = res.data.data.shopNo
                that.data.shop_name = res.data.data.shopName
                that.setData({shop_name: res.data.data.shopName})
              }else{
                Toast.fail(res.data.msg)
              }
            }, function () {
              
             })
          }else{
            Toast.fail('请使用巡检地点的二维码')
          }
        },
        fail: (res) => { console.log(res); }
      })
    }
  },
  goDeviceRecord(){
    wx.navigateTo({
      url: '/pages/welding/record/index',
    })
  },
  scanCode: function (res) {
    console.log('scanCode res',res)
    var that = this;
    var isLogin = app.getStorageSync("isLogin");
    var btntype = res.currentTarget.dataset.btntype;
    that.data.from_page = 'scancode'
    if (!isLogin) {
      wx.navigateTo({
        url: '/pages/login/index',
      })
    } else {
      if(that.data.isOpenWelding == 0){
        Toast('功能未开启')
        return;
      }
      wx.scanCode({
        success: (res) => {
            console.log("扫码结果", res);
            var qrcontent = res.result;
            console.log('扫码结果',qrcontent)
            var json_param = {}
            var linkParam = qrcontent;
            var qr_id = "";
            var qrtype = "";
            
          if(qrcontent.indexOf('https://') >= 0){
            var q = "?" + qrcontent.split("?")[1];
            var json_param = common_Js.getQueryVariable(q);
            var linkParam = "qrtype=range&no=" + json_param.no;
            if(qrcontent.indexOf('/range') >= 0){
              wx.navigateTo({ url: '/pages/device/range/feedRecord/index?id=' + json_param.id })
            } else if(qrcontent.indexOf('/welding') >= 0){
              that.onHttpDeviceDetail(json_param.id,btntype)
            }
          }else{
            //{\"qrtype\":\"range\",\"device_id\":" + rangeQrCode.getDeviceId() + ",\"qr_id\":" + rangeQrCode.getId()+"}
            if (qrcontent.indexOf('qrtype') < 0) {//加密过的数据
              qrcontent = CryptoJS.Decrypt(res.result)//解密
              console.log('解密：qrcontent',qrcontent)
              json_param = JSON.parse(qrcontent);
              qrtype = json_param["qrtype"];
              linkParam = "qrtype=" + json_param["qrtype"];
              if(qrcontent.indexOf('range') >= 0){
                linkParam += "&qr_id=" + json_param["qr_id"];
                qr_id = json_param["qr_id"];
              }
            }
            console.log('linkParam',linkParam)
            var is_range_indexof = qrcontent.indexOf('range');
            if (is_range_indexof >= 0) {
              wx.navigateTo({ url: '/pages/device/range/feedRecord/index?qr_id=' + qr_id})
            } else{
              Toast.fail('该二维码不属于该操作');
            }
          }
        },
        fail: (res) => { console.log(res); }
      })
    }
  },
  toapply: function (res) {
    var that = this;
    var isLogin = app.getStorageSync("isLogin");
    if (!isLogin) {
      wx.navigateTo({
        url: '/pages/login/index',
      })
    } else {
      // wx.navigateTo({
      //   url: '/pages/apply/addApply/index',
      // })
      wx.navigateTo({
        url: '/pages/apply/list/index',
      })
    }
  },
  /**
   * 获取页面数据的 http请求
   */
  onHttpDeviceDetail: function (device_id,btntype) {
    var that = this
    fetchApi.httpPost('/device/welding/detail', {
      device_id: device_id
    }, function (res) {
      console.log("设备详情数据返回", res)
      if (res.data.code == 0) {
          var device = res.data.data.device;
          console.log('device',device)
          if(device.isSelf == 0){//非固定区域

            // if(device.isSafe == 0 && btntype == 'guding'){
            //   Toast.fail('非固定区域设备，请先申请作业票');
            //   return;
            // }
            var company_id = app.getStorageSync("shop_id");
            if(device.shopId == company_id){
              // if(device.isSafe == 0){
              //   wx.navigateTo({ url: '/pages/welding/use/index?id=' + device_id});
              // }else{
              //   wx.navigateTo({ url: '/pages/welding/safeuse/index?id=' + device_id});
              // }
              wx.navigateTo({ url: '/pages/welding/safeuse/index?id=' + device_id});
            }else{
                Toast.fail('暂无使用权限');
            }
          }else{
            
            if(device.state == 0){
                wx.navigateTo({ url: '/pages/welding/active/index?id=' + device_id})
            }else{
                var user_id = app.getStorageSync("user_id");
                if(device.leaderWxUserId == user_id){
                  // if(device.isSafe == 0){
                  //   wx.navigateTo({ url: '/pages/welding/use/index?id=' + device_id});
                  // }else{
                  //   wx.navigateTo({ url: '/pages/welding/safeuse/index?id=' + device_id});
                  // }
                  wx.navigateTo({ url: '/pages/welding/safeuse/index?id=' + device_id});
                }else{
                    Toast.fail('暂无使用权限')
                }
            }
          }
      }else{
          Toast.fail(res.data.msg);
      }
      that.setData({
         isLoading: false, loading: true, netWork: true,
      })
    }, function (res) {
        that.setData({ hasData: false,  isLoading: false,  loading: true, netWork: true })
    })
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },
  openPhoneDialog:function(){
    var phone_num = this.data.phone_num==undefined?"":this.data.phone_num;
    console.log('phone_num',phone_num)
    phone_num = phone_num.replace(/去绑定/,"")
    this.setData({
      showPhoneDialog:true,
      phone_num: phone_num
    })
  },
  onClose:function(event){
    var that = this
    console.log('event',event)
    var btn = event.detail
    console.log('onDialogClose btn',btn)
    if(btn == 'confirm'){
      fetchApi.httpPost('/user/unBandShop', {
        shop_id: that.data.shop_id,
      }, function (res) {
        console.log('res', res)
        if(res.data.code == 0){
          Toast.success(res.data.msg)
          that.setData({shop_name:'未绑定企业'})
          that.data.shop_id = 0;
        }else{
          Toast.fail(res.data.msg)
        }
      }, function () {
        
       })
    }
  },
  shopNoInput:function(t){
    console.log('shopNoInput',t.detail.toUpperCase())
    this.setData({ shop_no: t.detail.toUpperCase() });
    this.data.shop_no = t.detail.toUpperCase()
  },
  phoneInput:function(t){
    console.log('shopNoInput',t.detail.toUpperCase())
    this.setData({ shop_no: t.detail.toUpperCase() });
    this.data.phone_num = t.detail.toUpperCase()
  },
  passwordsInput:function(t){
    console.log('passwordsInput',t.detail)
    this.setData({ passwords: t.detail });
    this.data.passwordsInput = t.detail
  },
  onDialogClose:function(event){
    var that = this
    if (that.data.shop_no == null || that.data.shop_no == '') {
      Toast.fail('请输入商户编码'); return;
    }
    console.log('onDialogClose',event)
    var btn = event.detail
    console.log('onDialogClose btn',btn)
    if(btn == 'confirm'){
      fetchApi.httpPost('/user/bandShop', {
        shop_no: that.data.shop_no,
      }, function (res) {
        console.log('res', res)
        if(res.data.code == 0){
          Toast.success(res.data.msg)
          that.data.shop_id = res.data.data.id
          that.data.shop_no = res.data.data.shopNo
          that.data.shop_name = res.data.data.shopName
          that.setData({shop_name: res.data.data.shopName})
        }else{
          Toast.fail(res.data.msg)
        }
      }, function () {
        
       })
    }
  },
  /**
  * 页面相关事件处理函数--监听用户下拉动作
  */
  onPullDownRefresh: function () {
    var that = this
    var isLogin = app.getStorageSync("isLogin");
    console.log('isLogin',isLogin)
    this.setData({
      isLoading:true,
      loading: true, netWork: true,
      isLogin: isLogin
    });
    if(isLogin == 1){
      that.onHttpGetUserInfo()
    }
  },
  onDialogPhoneClose:function(event){
    var that = this
    
    console.log('onDialogPhoneClose',event)
    var btn = event.detail
    console.log('onDialogPhoneClose btn',btn)
    if(btn == 'confirm'){
      if (that.data.phone_num == null || that.data.phone_num == '') {
        Toast.fail('请输入手机号'); 
        this.setData({phone_num:"去绑定"})
        return;
      }
      
      if (!that.data.is_test || that.data.is_test != 1) {
        if (that.data.passwords == null || that.data.passwords == '') {
          Toast.fail('请输入此手机号后台密码'); 
          return;
        }
      }
      fetchApi.httpPost('/user/bandPhone', {
        phone_num: that.data.phone_num.replace('去绑定',''),
        passwords: that.data.passwords,
      }, function (res) {
        console.log('res', res)
        if(res.data.code == 0){
          Toast.success(res.data.msg)
          that.setData({
            phone_num: that.data.phone_num,
            shop_name: res.data.data.shop_name,
            shop_id: res.data.data.shop_id
          })
          that.data.shop_id=res.data.data.shop_id
          app.setStorageSync("phone_num", res.data.data.phone_num);
          app.setStorageSync("shop_name", res.data.data.shop_name);
          app.setStorageSync("shop_id", res.data.data.shop_id);
        }else{
          Toast.fail(res.data.msg)
        }
      }, function () {
        
       })
    }
  },
  goLogin:function(){
    wx.navigateTo({
      url: '/pages/login/index',
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    return {
      title: "",
      success: function (res) {
        console.log(res, "转发成功")
      },
      fail: function (res) {
        console.log(res, "转发失败")
      }
    }
  }
})